package co.yixiang.modules.pay;

import cn.hutool.core.util.ObjectUtil;
import co.yixiang.api.ApiResult;
import co.yixiang.constant.SystemConfigConstants;
import co.yixiang.enums.*;
import co.yixiang.modules.auction.domain.YxAuctionMember;
import co.yixiang.modules.auction.domain.YxAuctionOrder;
import co.yixiang.modules.auction.domain.YxAuctionRecord;
import co.yixiang.modules.auction.service.YxAuctionMemberService;
import co.yixiang.modules.auction.service.mapper.YxAuctionOrderMapper;
import co.yixiang.modules.auction.service.mapper.YxAuctionRecordMapper;
import co.yixiang.modules.commom.domain.YxAppdict;
import co.yixiang.modules.commom.service.YxAppdictService;
import co.yixiang.modules.news.domain.YxNews;
import co.yixiang.modules.news.domain.YxUserNews;
import co.yixiang.modules.news.service.YxNewsService;
import co.yixiang.modules.news.service.YxUserNewsService;
import co.yixiang.modules.order.domain.YxStoreOrder;
import co.yixiang.modules.order.domain.YxStoreOrderCartInfo;
import co.yixiang.modules.order.domain.YxStoreOrderStatus;
import co.yixiang.modules.order.service.YxStoreOrderCartInfoService;
import co.yixiang.modules.order.service.mapper.StoreOrderMapper;
import co.yixiang.modules.order.service.mapper.StoreOrderStatusMapper;
import co.yixiang.modules.pay.weixin.WeiXinUtil;
import co.yixiang.modules.pay.weixin.WxPayReturnData;
import co.yixiang.modules.pay.weixin.WxPaySendData;
import co.yixiang.modules.pay.zhifubao.AlipayConfig;
import co.yixiang.modules.pay.zhifubao.EmptyUtils;
import co.yixiang.modules.product.service.YxStoreProductService;
import co.yixiang.modules.shop.service.YxSystemConfigService;
import co.yixiang.modules.user.domain.*;
import co.yixiang.modules.user.service.YxUserBillService;
import co.yixiang.modules.user.service.YxUserRechargeService;
import co.yixiang.modules.user.service.YxUserService;
import co.yixiang.modules.user.service.YxUserinfoService;
import co.yixiang.modules.user.service.mapper.YxDistributorEarningsMapper;
import co.yixiang.modules.user.service.mapper.YxDistributorRelationMapper;
import co.yixiang.utils.RandonOrderNoUtil;
import co.yixiang.utils.RedisUtils;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import net.sf.json.JSONObject;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class AppPayService {

    @Autowired
    private YxUserBillService yxUserBillService;
    @Autowired
    private YxUserService yxUserService;
    @Autowired
    private YxUserinfoService yxUserinfoService;
    @Autowired
    private YxAppdictService yxAppdictService;
    @Autowired
    private YxAuctionRecordMapper yxAuctionRecordMapper;
    @Autowired
    private YxAuctionOrderMapper yxAuctionOrderMapper;
    @Autowired
    private StoreOrderMapper storeOrderMapper;
    @Autowired
    private StoreOrderStatusMapper storeOrderStatusMapper;
    @Autowired
    private  YxStoreProductService yxStoreProductService;
    @Autowired
    private  YxUserNewsService yxUserNewsService;
    @Autowired
    private  YxNewsService yxNewsService;
    @Autowired
    private  YxStoreOrderCartInfoService yxStoreOrderCartInfoService;
    @Autowired
    private YxDistributorRelationMapper  yxDistributorRelationMapper;
    @Autowired
    private YxDistributorEarningsMapper yxDistributorEarningsMapper;
    @Autowired
    private  RedisUtils redisUtil;
    @Autowired
    private YxAuctionMemberService auctionMemberService;
    @Autowired
    private YxUserRechargeService userRechargeService;

    /**
     * 付款
     *
     * @return
     */
    public ApiResult payment(HttpServletRequest request, int type, String num , BigDecimal money){
        String basePath = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/";
        JSONObject jsonObject = new JSONObject();
        if (type == 1) {//支付宝支付
            //实例化客户端
            AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", AlipayConfig.APPID,
                    AlipayConfig.private_key, "json", AlipayConfig.input_charset, AlipayConfig.ali_public_key, "RSA2");
            //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
            AlipayTradeAppPayRequest payrequest = new AlipayTradeAppPayRequest();
            //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
            AlipayTradeAppPayModel alipaymodel = new AlipayTradeAppPayModel();
            alipaymodel.setBody("paimai");
            alipaymodel.setSubject("paimai");
            alipaymodel.setOutTradeNo(num);//订单号
            alipaymodel.setTimeoutExpress("30m");
            alipaymodel.setTotalAmount(String.valueOf(money));
            alipaymodel.setProductCode("QUICK_MSECURITY_PAY");
            payrequest.setBizModel(alipaymodel);
            payrequest.setNotifyUrl(basePath+ "pay/aliyunReturn");
            try {
                //这里和普通的接口调用不同，使用的是sdkExecute
                AlipayTradeAppPayResponse response = alipayClient.sdkExecute(payrequest);
                System.out.println("~~~~~~~~~~~~~~~~~" + response);
                System.out.println("--------------" + response.getBody());//就是orderString 可以直接给客户端请求，无需再做处理。
                return ApiResult.ok(response);
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }

        } else if (type == 2) {  //微信支付
            jsonObject.put("weixin", weixinDoPay(request, basePath, num, money));
            jsonObject.put("type", 2);
            if (String.valueOf(jsonObject).equals("-1") || EmptyUtils.isEmpty(jsonObject.get("weixin"))) {
                return ApiResult.fail("下单失败");
            }
            System.out.println("-------------------下单成功------------------------");
            return ApiResult.ok(String.valueOf(jsonObject));
        }
        return ApiResult.ok();
    }

    /**
     * 微信支付配置类
     *
     * @param request
     * @param number
     * @param totalPrice
     * @return
     */
    public Map<String, Object> weixinDoPay(HttpServletRequest request, String basePath, String number, BigDecimal totalPrice) {
        System.out.println("=====================微信支付开始================");
        WxPaySendData wxPaySendData = new WxPaySendData();
        if (EmptyUtils.isNotEmpty(number) && EmptyUtils.isNotEmpty(totalPrice)) {
            //普通用户
            wxPaySendData.setAppid(WeiXinUtil.WEIXIN_APP_ID); // 微信开放平台核通过的应用APPID
            wxPaySendData.setAttach("yitong"); // 附加数据，在查询API和支付通知中原样返回，该字段主要用于商户携带订单的自定义数据
            //普通用户
            wxPaySendData.setMch_id(WeiXinUtil.WEIXIN_MCH_ID); // 微信支付分配的商户号

            wxPaySendData.setBody("yitong-No：" + number); //商品或支付单简要描述
            wxPaySendData.setNonce_str(WeiXinUtil.getNonceStr()); // 随机字符串，不长于32位
            wxPaySendData.setNotify_url(basePath+"pay/weixinReturnUrl");// 回调地址
            wxPaySendData.setTotal_fee(totalPrice.multiply(new BigDecimal(100)).intValue());
            wxPaySendData.setSpbill_create_ip(WeiXinUtil.getClientIp(request));
            wxPaySendData.setOut_trade_no(number); // 商户订单号
            wxPaySendData.setTrade_type("APP"); // 支付类型
            // 请求
            String returnXml = WeiXinUtil.unifiedOrder(wxPaySendData, WeiXinUtil.WEIXIN_PAY_KEY);
            WxPayReturnData reData = new WxPayReturnData();
            XStream xs1 = new XStream(new DomDriver());
            xs1.alias("xml", WxPayReturnData.class);
            reData = (WxPayReturnData) xs1.fromXML(returnXml);
            System.out.println("===========reData.getReturn_code()=======：" + reData.getReturn_code());
            if (reData.getReturn_code().equals("SUCCESS") && reData.getResult_code().equals("SUCCESS")) {
                String timeStamp = WeiXinUtil.getTimeStamp(); // 时间戳
                String _package = "prepay_id=" + reData.getPrepay_id();
                SortedMap<Object, Object> signMap = new TreeMap<Object, Object>();
                signMap.put("appid", reData.getAppid());
                signMap.put("timestamp", timeStamp);
                signMap.put("noncestr", reData.getNonce_str());
                signMap.put("package", _package);
                signMap.put("signtype", "MD5");
                String paySign = WeiXinUtil.createSign(signMap, WeiXinUtil.WEIXIN_PAY_KEY);
                wxPaySendData.setSign(paySign);
                SortedMap<Object, Object> iosSignMap = new TreeMap<Object, Object>();
                iosSignMap.put("appid", wxPaySendData.getAppid());
                iosSignMap.put("partnerid", wxPaySendData.getMch_id());
                iosSignMap.put("prepayid", reData.getPrepay_id());
                iosSignMap.put("package", "Sign=WXPay");
                iosSignMap.put("noncestr", wxPaySendData.getNonce_str());
                iosSignMap.put("timestamp", timeStamp);
                System.out.println("---------------签名111------------------" + JSONObject.fromObject(iosSignMap).toString());
                String iosSign = WeiXinUtil.createSign(iosSignMap, WeiXinUtil.WEIXIN_PAY_KEY); // IOS端需要的SIGN
                System.out.println("---------------签名222------------------" + iosSign);
                Map<String, Object> map2 = new HashMap<String, Object>();
                map2.put("timestamp", timeStamp);
                map2.put("prepayid", reData.getPrepay_id());
                map2.put("sign", iosSign);
                map2.put("noncestr", wxPaySendData.getNonce_str());
                map2.put("package", "Sign=WXPay");
                map2.put("partnerid", wxPaySendData.getMch_id());
                map2.put("appid", wxPaySendData.getAppid());
                System.out.println("===================nonceStr===============" + wxPaySendData.getNonce_str());
                return map2;
            }
            System.out.println("===========微信支付结束了。。。。===========================");
        }
        System.out.println("===========微信支付返回为空。。。。===========================");
        return null;
    }


    /**
     * 功能描述:微信支付结果通知
     *
     * @param request
     * @throws Exception
     */
    @Transactional
    public ApiResult weixinPayResult(HttpServletRequest request) throws Exception {
        Map<String, String> requestMap =parseXml(request);
        System.out.println("---------------------微信支付回调333---------------------------" + JSONObject.fromObject(requestMap).toString());
        System.out.println("requestMap:" + requestMap.toString());
        if (requestMap.get("result_code").equals("SUCCESS")) {  //支付成功
            String outTradeNo = requestMap.get("out_trade_no");   //订单编号
            String transactionId = requestMap.get("transaction_id"); // 微信中的订单号
            String openid = requestMap.get("openid");// 用户唯一标识
            if(outTradeNo.contains("chongzhi")){
                updateUser(outTradeNo,transactionId);
            }
            if(outTradeNo.contains("serviceMoney")){
                updateAuctionOrder(outTradeNo,transactionId);
            }
            if(outTradeNo.contains("order")){
                updateOrder(outTradeNo,transactionId);
            }
            if(outTradeNo.contains("totalMoney")){
                updateOneKeyAuctionOrder(outTradeNo,transactionId);
            }
            if (outTradeNo.contains("openMember")){
                openMemberSuccess(outTradeNo , transactionId);
            }
            if(outTradeNo.contains("recharge")){//充值回调
                rechargeSuccess(outTradeNo,transactionId);
            }
            return ApiResult.ok("成功");
        }
        return ApiResult.fail("");
    }

    private void rechargeSuccess(String outTradeNo, String orderNo) {

        YxUserRecharge userRecharge = userRechargeService.getOne(new QueryWrapper<YxUserRecharge>().lambda()
                .eq(YxUserRecharge::getOrderId, outTradeNo));
        if (ObjectUtil.isEmpty(userRecharge) || userRecharge.getPaid() == 1) return;
        userRecharge.setPaid(1);
        userRecharge.setApprovalStatus(2);
        userRechargeService.updateById(userRecharge);
        //修改押金
        BigDecimal nowPrice = new BigDecimal(String.valueOf(redisUtil.get("UserPrice" + userRecharge.getUid())));
        BigDecimal add = nowPrice.add(userRecharge.getPrice());
        redisUtil.set("UserPrice" + userRecharge.getUid() , add.setScale(2 , BigDecimal.ROUND_HALF_UP));

        //修改押金金额
        YxUser yxUser=yxUserService.getById(userRecharge.getUid());
        if(null !=yxUser){
            yxUser.setNowMoney(add);
            yxUserService.updateById(yxUser);
        }

        //增加记录
        YxUserBill userBill = YxUserBill.builder()
                .uid(yxUser.getUid())
                .title("充值")
                .category(BillDetailEnum.CATEGORY_1.getValue())
                .type(BillDetailEnum.TYPE_1.getValue())
                .number(userRecharge.getPrice())
                .balance(add)
                .mark("充值")
                .status(BillEnum.STATUS_1.getValue())
                .payType(3)
                .orderNo(orderNo)
                .pm(BillEnum.PM_1.getValue())
                .build();
        yxUserBillService.save(userBill);
    }

    public void openMemberSuccess(String outTradeNo, String transactionId) {
        YxUserBill userBill = yxUserBillService.getOne(new QueryWrapper<YxUserBill>().lambda()
                .eq(YxUserBill::getOrderNo, outTradeNo));
        if (ObjectUtil.isEmpty(userBill) || userBill.getStatus() == BillEnum.STATUS_1.getValue()) return;
        //修改记录状态
        userBill.setStatus(BillEnum.STATUS_1.getValue());
        userBill.setIsPay(1);
        yxUserBillService.updateById(userBill);
        //增加天数
        YxAuctionMember auctionMember = auctionMemberService.getById(userBill.getLinkId());
        YxUser user = yxUserService.getById(userBill.getUid());
        Calendar calendar = Calendar.getInstance();
        if (ObjectUtil.isNotEmpty(user.getMemberTime()) && user.getMemberTime().getTime() > calendar.getTime().getTime()){
            //过期或未开通
            calendar.setTime(user.getMemberTime());
        }
        calendar.add(Calendar.DATE , auctionMember.getTime());
        user.setMemberTime(calendar.getTime());
        yxUserService.updateById(user);
    }


    @SuppressWarnings("unchecked")
    public static Map<String, String> parseXml(HttpServletRequest request) throws Exception {
        // 将解析结果存储在HashMap中
        Map<String, String> map = new HashMap<String, String>();

        // 从request中取得输入流
        InputStream inputStream = request.getInputStream();
        // 读取输入流
        SAXReader reader = new SAXReader();
        Document document = reader.read(inputStream);
        // 得到xml根元素
        Element root = document.getRootElement();
        // 得到根元素的所有子节点
        List<Element> elementList = root.elements();

        // 遍历所有子节点
        for (Element e : elementList)
            map.put(e.getName(), e.getText());

        // 释放资源
        inputStream.close();
        inputStream = null;

        return map;
    }

    /**
     * 功能描述：支付宝支付通知接口
     *
     * @param request 请求参数
     * @return 返回int型结果
     * @throws NumberFormatException 数字格式化异常
     * @throws Exception             异常
     */
    @Transactional
    public ApiResult zhifubaoPayResult(HttpServletRequest request) throws NumberFormatException, Exception {
        System.out.println("--------------------支付回调333------------------------");
        Map<String, String> paramsMap = updateMap(request);
        String payParamsMap = JSONObject.fromObject(paramsMap).toString();
        System.out.println("--------------------" + JSONObject.fromObject(paramsMap).toString());
        String outTradeNo = paramsMap.get("out_trade_no");    //订单流水号
        String orderNo = paramsMap.get("trade_no");         // 支付宝订单号
        String tradeStatus = paramsMap.get("trade_status"); //付款状态
        boolean isVerify = true;//AlipayNotify.verify(paramsMap);       //验证参数
        System.out.println("isVerify:" + isVerify);
        if (isVerify == true && "TRADE_SUCCESS".equalsIgnoreCase(tradeStatus)) {//支付成功，进行业务处理
            if(outTradeNo.contains("chongzhi")){
                updateUser(outTradeNo,orderNo);
            }
            if(outTradeNo.contains("serviceMoney")){
                updateAuctionOrder(outTradeNo,orderNo);
            }
            if(outTradeNo.contains("totalMoney")){
                updateOneKeyAuctionOrder(outTradeNo,orderNo);
            }
            if(outTradeNo.contains("order")){
                updateOrder(outTradeNo,orderNo);
            }

            return ApiResult.ok("支付成功");
        }else{
            return ApiResult.fail("支付失败");
        }

    }

    private void updateOneKeyAuctionOrder(String orderNo, String outTradeNo) {
        YxUserBill yxUserBill= yxUserBillService.selectByOrderNo(orderNo);
        if(null !=yxUserBill && 0==yxUserBill.getStatus()){
            yxUserBill.setOutOrderNo(outTradeNo);
            yxUserBill.setStatus(BillEnum.STATUS_1.getValue());
            yxUserBillService.updateById(yxUserBill);
            //修改个人信息消费等级
            YxUserinfo yxUserinfo=yxUserinfoService.selectByUserId(yxUserBill.getUid());
            if(null !=yxUserinfo){
                yxUserinfo.setBuyMoney(yxUserinfo.getBuyMoney().add(yxUserBill.getNumber()));
                YxAppdict levelAppdict=yxAppdictService.selectMoneyByMoney(yxUserinfo.getBuyMoney());
                if(null !=levelAppdict){
                    yxUserinfo.setBuyLevel(Integer.valueOf(levelAppdict.getName()));
                }
                yxUserinfoService.updateById(yxUserinfo);
            }
            String[] idsArray = yxUserBill.getLinkId().split(";");
            List<String> stringList = Arrays.asList(idsArray);
            for (String id:stringList
                 ) {
                YxAuctionOrder yxAuctionOrder=yxAuctionOrderMapper.selectById(id);
                if(null !=yxAuctionOrder && 4 !=yxAuctionOrder.getStatus()){
                    YxAuctionRecord yxAuctionRecord=yxAuctionRecordMapper.selectById(yxAuctionOrder.getAuctionRecordId());
                    //获取溢价比例
                    YxAppdict yxAppdict=yxAppdictService.findAppdictByCode("yjbl");
                    BigDecimal nextPrice =yxAuctionRecord.getPrice().multiply(new BigDecimal(yxAppdict.getMemo())).add(yxAuctionRecord.getPrice());
                    //设置新的抢拍单
                    YxAuctionRecord newYxAuctionRecord=new YxAuctionRecord();
                    newYxAuctionRecord.setAuctionProductId(yxAuctionRecord.getAuctionProductId());
                    newYxAuctionRecord.setPrice(nextPrice);
                    if(yxAuctionRecord.getTopPrice().compareTo(nextPrice)==-1){
                        newYxAuctionRecord.setIsMax(1);
                    }
                    newYxAuctionRecord.setCreateTime(new Date());
                    newYxAuctionRecord.setTopPrice(yxAuctionRecord.getTopPrice());
                    YxAppdict sxf=yxAppdictService.findAppdictByCode("sxf");
                    if(null !=sxf){
                        newYxAuctionRecord.setServiceCharge(nextPrice.multiply(new BigDecimal(sxf.getMemo())));
                    }else{
                        newYxAuctionRecord.setServiceCharge(nextPrice.multiply(new BigDecimal(0.025)));
                    }
                    newYxAuctionRecord.setFirstCommission(yxAuctionRecord.getFirstCommission());
                    newYxAuctionRecord.setSecondCommission(yxAuctionRecord.getSecondCommission());

                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
                    Calendar  calendar =Calendar.getInstance();
                    calendar.setTime(new Date());
                    calendar.add(calendar.DATE,1);
                    String startTime = simpleDateFormat.format(calendar.getTime());
                    newYxAuctionRecord.setStartTime(startTime);
                    newYxAuctionRecord.setTimeId(yxAuctionRecord.getTimeId());
                    newYxAuctionRecord.setUserId(yxUserBill.getUid());
                    if(0==yxAuctionRecord.getParentId()){
                        newYxAuctionRecord.setParentId(yxAuctionRecord.getId());
                    }else{
                        newYxAuctionRecord.setParentId(yxAuctionRecord.getParentId());
                    }
                    yxAuctionRecordMapper.insert(newYxAuctionRecord);
                    redisUtil.set("paimai"+newYxAuctionRecord.getId(),newYxAuctionRecord.getId());
                    //修改买单表
                    yxAuctionOrder.setStatus(AuctionOrderEnum.TYPE_4.getValue());
                    yxAuctionOrder.setIsPayService(1);
                    yxAuctionOrder.setSellPrice(nextPrice);
                    yxAuctionOrder.setReceiveType(AuctionOrderEnum.RECEIVE_1.getValue());
                    yxAuctionOrderMapper.updateById(yxAuctionOrder);
                    //一级分佣比例
                    YxAppdict storeBrokerageRatioStr = yxAppdictService.findAppdictByCode("yjyj");
                    //二级分佣比例
                    YxAppdict storeBrokerageTwoStr = yxAppdictService.findAppdictByCode("ejyj");
                    //获取一级分佣用户信息
                    YxDistributorRelation firstYxDistributorRelation=yxDistributorRelationMapper.getByUid(yxUserBill.getUid());
                    if(null !=firstYxDistributorRelation){
                        YxDistributorEarnings yxDistributorEarnings=new YxDistributorEarnings();
                        yxDistributorEarnings.setIsOver(1);
                        yxDistributorEarnings.setType(1);
                        if(null !=storeBrokerageRatioStr){
                            yxDistributorEarnings.setPrice(yxAuctionOrder.getServiceMoney().multiply(new BigDecimal(storeBrokerageRatioStr.getMemo()).divide(new BigDecimal(100))));
                        }else{
                            yxDistributorEarnings.setPrice(yxAuctionOrder.getServiceMoney().multiply(new BigDecimal(20).divide(new BigDecimal(100))));
                        }
                        yxDistributorEarnings.setStatus(1);
                        yxDistributorEarnings.setUid(firstYxDistributorRelation.getPUid());
                        yxDistributorEarnings.setDUid(yxUserBill.getUid());
                        yxDistributorEarningsMapper.insert(yxDistributorEarnings);
                        YxUser firstUser=yxUserService.getById(firstYxDistributorRelation.getPUid());
                        if(null !=firstUser){
                            firstUser.setBrokeragePrice(firstUser.getBrokeragePrice().add(yxDistributorEarnings.getPrice()));
                            yxUserService.updateById(firstUser);
                        }
                        //获取二级分佣用户信息
                        YxDistributorRelation secondYxDistributorRelation=yxDistributorRelationMapper.getByUid(firstYxDistributorRelation.getPUid());
                        if(null !=secondYxDistributorRelation){
                            YxDistributorEarnings syxDistributorEarnings=new YxDistributorEarnings();
                            syxDistributorEarnings.setIsOver(1);
                            if(null !=storeBrokerageTwoStr){
                                syxDistributorEarnings.setPrice(yxAuctionOrder.getServiceMoney().multiply(new BigDecimal(storeBrokerageTwoStr.getMemo()).divide(new BigDecimal(100))));
                            }else{
                                syxDistributorEarnings.setPrice(yxAuctionOrder.getServiceMoney().multiply(new BigDecimal(10).divide(new BigDecimal(100))));
                            }
                            syxDistributorEarnings.setStatus(1);
                            yxDistributorEarnings.setType(1);
                            syxDistributorEarnings.setUid(secondYxDistributorRelation.getPUid());
                            syxDistributorEarnings.setDUid(yxUserBill.getUid());
                            yxDistributorEarningsMapper.insert(syxDistributorEarnings);
                            YxUser syxUser=yxUserService.getById(secondYxDistributorRelation.getPUid());
                            if(null !=syxUser){
                                syxUser.setBrokeragePrice(syxUser.getBrokeragePrice().add(syxDistributorEarnings.getPrice()));
                                yxUserService.updateById(syxUser);
                            }
                        }
                    }
            }


            }
        }
    }

    //订单支付回调
    private void updateOrder(String orderNo, String outTradeNo) {
        YxUserBill yxUserBill= yxUserBillService.selectByOrderNo(orderNo);
        if(null !=yxUserBill && 0==yxUserBill.getStatus()){
            yxUserBill.setOutOrderNo(outTradeNo);
            yxUserBill.setStatus(BillEnum.STATUS_1.getValue());
            yxUserBillService.updateById(yxUserBill);
            //修改个人信息消费等级
            YxUserinfo yxUserinfo=yxUserinfoService.selectByUserId(yxUserBill.getUid());
            YxStoreOrder yxStoreOrder=storeOrderMapper.selectById(yxUserBill.getLinkId());
            if(null !=yxUserinfo){
                yxUserinfo.setBuyMoney(yxUserinfo.getBuyMoney().add(yxStoreOrder.getPayPrice()));
                YxAppdict levelAppdict=yxAppdictService.selectMoneyByMoney(yxUserinfo.getBuyMoney());
                if(null !=levelAppdict){
                    yxUserinfo.setBuyLevel(Integer.valueOf(levelAppdict.getName()));
                }
                yxUserinfoService.updateById(yxUserinfo);
            }
            //修改订单状态
            if(null !=yxStoreOrder && 0==yxStoreOrder.getPaid()){
                YxUser yxUser=yxUserService.getById(yxStoreOrder.getUid());
                //积分流水入库
                if(yxStoreOrder.getTotalIntegral().compareTo(new BigDecimal(0))>0){
                    //金额流水入库
                    YxUserBill integralBill = YxUserBill.builder()
                            .uid(yxStoreOrder.getUid())
                            .title("购买商品")
                            .linkId(yxStoreOrder.getId().toString())
                            .type(BillDetailEnum.TYPE_3.getValue())
                            .category(BillDetailEnum.CATEGORY_2.getValue())
                            .number(yxStoreOrder.getTotalIntegral())
                            .balance(yxUser.getIntegral())
                            .mark("购买商品")
                            .status(BillEnum.STATUS_1.getValue())
                            .payType(yxUserBill.getPayType())
                            .orderNo("order"+ RandonOrderNoUtil.getOrderIdByTime())
                            .pm(BillEnum.PM_0.getValue())
                            .build();
                    yxUserBillService.save(integralBill);
                    yxUser.setIntegral(yxUser.getIntegral().subtract(yxStoreOrder.getTotalIntegral()));
                    yxUserService.updateById(yxUser);
                }
                yxStoreOrder.setPaid(OrderInfoEnum.PAY_STATUS_1.getValue());
                yxStoreOrder.setPayType(yxUserBill.getPayType().toString());
                yxStoreOrder.setStatus(OrderStatusEnum.STATUS_1.getValue());
                yxStoreOrder.setPayTime(new Date());
                storeOrderMapper.updateById(yxStoreOrder);
                //增加状态
                YxStoreOrderStatus storeOrderStatus = new YxStoreOrderStatus();
                storeOrderStatus.setOid(yxStoreOrder.getId());
                storeOrderStatus.setChangeType(OrderLogEnum.PAY_ORDER_SUCCESS.getValue());
                storeOrderStatus.setChangeMessage(OrderLogEnum.PAY_ORDER_SUCCESS.getDesc());
                storeOrderStatusMapper.insert(storeOrderStatus);
                //生成消息  --- 支付成功
                YxNews yxNews = new YxNews();
                yxNews.setTitle("支付成功");
                yxNews.setSynopsis("共"+yxStoreOrder.getTotalNum()+"件商品");
                List<YxStoreOrderCartInfo> list = yxStoreOrderCartInfoService.list(new QueryWrapper<YxStoreOrderCartInfo>().lambda()
                        .eq(YxStoreOrderCartInfo::getOid, yxStoreOrder.getId())
                        .last("LIMIT 1"));
                yxNews.setImage(yxStoreProductService.getById(list.get(0).getProductId()).getImage());
                yxNews.setObjectId(Long.valueOf(yxStoreOrder.getOrderId()));
                yxNews.setType(3);

                YxUserNews userNews = new YxUserNews();
                userNews.setUserId(yxStoreOrder.getUid());
                yxNewsService.save(yxNews);
                userNews.setNewsId(yxNews.getId());
                yxUserNewsService.save(userNews);
            }
        }
    }

    //转拍回调
    private void updateAuctionOrder(String orderNo, String outTradeNo) throws ParseException {
        YxUserBill yxUserBill= yxUserBillService.selectByOrderNo(orderNo);
        if(null !=yxUserBill && 0==yxUserBill.getStatus()){
            yxUserBill.setOutOrderNo(outTradeNo);
            yxUserBill.setStatus(BillEnum.STATUS_1.getValue());
            yxUserBillService.updateById(yxUserBill);
            //修改个人信息消费等级
            YxUserinfo yxUserinfo=yxUserinfoService.selectByUserId(yxUserBill.getUid());
            YxAuctionOrder yxAuctionOrder=yxAuctionOrderMapper.selectById(yxUserBill.getLinkId());
            if(null !=yxUserinfo){
                yxUserinfo.setBuyMoney(yxUserinfo.getBuyMoney().add(yxAuctionOrder.getServiceMoney()));
                YxAppdict levelAppdict=yxAppdictService.selectMoneyByMoney(yxUserinfo.getBuyMoney());
                if(null !=levelAppdict){
                    yxUserinfo.setBuyLevel(Integer.valueOf(levelAppdict.getName()));
                }
                yxUserinfoService.updateById(yxUserinfo);
            }
            if(null !=yxAuctionOrder && 4 !=yxAuctionOrder.getStatus()){
               YxAuctionRecord yxAuctionRecord=yxAuctionRecordMapper.selectById(yxAuctionOrder.getAuctionRecordId());
                //获取溢价比例
                YxAppdict yxAppdict=yxAppdictService.findAppdictByCode("yjbl");
                BigDecimal nextPrice =yxAuctionRecord.getPrice().multiply(new BigDecimal(yxAppdict.getMemo())).add(yxAuctionRecord.getPrice());
                //设置新的抢拍单
                YxAuctionRecord newYxAuctionRecord=new YxAuctionRecord();
                newYxAuctionRecord.setAuctionProductId(yxAuctionRecord.getAuctionProductId());
                newYxAuctionRecord.setPrice(nextPrice);
                newYxAuctionRecord.setCreateTime(new Date());
                newYxAuctionRecord.setTopPrice(yxAuctionRecord.getTopPrice());
                BigDecimal topPrice=yxAuctionRecord.getTopPrice();
                if(topPrice.compareTo(nextPrice)==-1){
                    newYxAuctionRecord.setIsMax(1);
                }
                YxAppdict sxf=yxAppdictService.findAppdictByCode("sxf");
                if(null !=sxf){
                    newYxAuctionRecord.setServiceCharge(nextPrice.multiply(new BigDecimal(sxf.getMemo())));
                }else{
                    newYxAuctionRecord.setServiceCharge(nextPrice.multiply(new BigDecimal(0.025)));
                }
                newYxAuctionRecord.setFirstCommission(yxAuctionRecord.getFirstCommission());
                newYxAuctionRecord.setSecondCommission(yxAuctionRecord.getSecondCommission());

                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
                Calendar  calendar =Calendar.getInstance();
                calendar.setTime(new Date());
                calendar.add(calendar.DATE,1);
                String startTime = simpleDateFormat.format(calendar.getTime());
                newYxAuctionRecord.setStartTime(startTime);
                newYxAuctionRecord.setTimeId(yxAuctionRecord.getTimeId());
                newYxAuctionRecord.setUserId(yxUserBill.getUid());
                if(0==yxAuctionRecord.getParentId()){
                    newYxAuctionRecord.setParentId(yxAuctionRecord.getId());
                }else{
                    newYxAuctionRecord.setParentId(yxAuctionRecord.getParentId());
                }
                yxAuctionRecordMapper.insert(newYxAuctionRecord);
                redisUtil.set("paimai"+newYxAuctionRecord.getId(),newYxAuctionRecord.getId());
                //修改买单表
                yxAuctionOrder.setStatus(AuctionOrderEnum.TYPE_4.getValue());
                yxAuctionOrder.setIsPayService(1);
                yxAuctionOrder.setSellPrice(nextPrice);
                yxAuctionOrder.setReceiveType(AuctionOrderEnum.RECEIVE_1.getValue());
                yxAuctionOrderMapper.updateById(yxAuctionOrder);
                //一级分佣比例
                YxAppdict storeBrokerageRatioStr = yxAppdictService.findAppdictByCode("yjyj");
                //二级分佣比例
                YxAppdict storeBrokerageTwoStr = yxAppdictService.findAppdictByCode("ejyj");
                //获取一级分佣用户信息
                YxDistributorRelation firstYxDistributorRelation=yxDistributorRelationMapper.getByUid(yxUserBill.getUid());
                if(null !=firstYxDistributorRelation){
                    YxDistributorEarnings yxDistributorEarnings=new YxDistributorEarnings();
                    yxDistributorEarnings.setIsOver(1);
                    yxDistributorEarnings.setType(1);
                    if(null !=storeBrokerageRatioStr){
                        yxDistributorEarnings.setPrice(yxAuctionOrder.getServiceMoney().multiply(new BigDecimal(storeBrokerageRatioStr.getMemo()).divide(new BigDecimal(100))));
                    }else{
                        yxDistributorEarnings.setPrice(yxAuctionOrder.getServiceMoney().multiply(new BigDecimal(20).divide(new BigDecimal(100))));
                    }
                    yxDistributorEarnings.setStatus(1);
                    yxDistributorEarnings.setUid(firstYxDistributorRelation.getPUid());
                    yxDistributorEarnings.setDUid(yxUserBill.getUid());
                    yxDistributorEarningsMapper.insert(yxDistributorEarnings);
                    YxUser firstUser=yxUserService.getById(firstYxDistributorRelation.getPUid());
                    if(null !=firstUser){
                        firstUser.setBrokeragePrice(firstUser.getBrokeragePrice().add(yxDistributorEarnings.getPrice()));
                        yxUserService.updateById(firstUser);
                    }
                    //获取二级分佣用户信息
                    YxDistributorRelation secondYxDistributorRelation=yxDistributorRelationMapper.getByUid(firstYxDistributorRelation.getPUid());
                    if(null !=secondYxDistributorRelation){
                        YxDistributorEarnings syxDistributorEarnings=new YxDistributorEarnings();
                        syxDistributorEarnings.setIsOver(1);
                        if(null !=storeBrokerageTwoStr){
                            syxDistributorEarnings.setPrice(yxAuctionOrder.getServiceMoney().multiply(new BigDecimal(storeBrokerageTwoStr.getMemo()).divide(new BigDecimal(100))));
                        }else{
                            syxDistributorEarnings.setPrice(yxAuctionOrder.getServiceMoney().multiply(new BigDecimal(10).divide(new BigDecimal(100))));
                        }
                        syxDistributorEarnings.setStatus(1);
                        yxDistributorEarnings.setType(1);
                        syxDistributorEarnings.setUid(secondYxDistributorRelation.getPUid());
                        syxDistributorEarnings.setDUid(yxUserBill.getUid());
                        yxDistributorEarningsMapper.insert(syxDistributorEarnings);
                        YxUser syxUser=yxUserService.getById(secondYxDistributorRelation.getPUid());
                        if(null !=syxUser){
                            syxUser.setBrokeragePrice(syxUser.getBrokeragePrice().add(syxDistributorEarnings.getPrice()));
                            yxUserService.updateById(syxUser);
                        }
                    }
                }

            }
        }
    }

    //充值回调处理
    private void updateUser(String orderNo, String outTradeNo) {
        YxUserBill yxUserBill= yxUserBillService.selectByOrderNo(orderNo);
        if(null !=yxUserBill && 0==yxUserBill.getStatus()){
            yxUserBill.setOutOrderNo(outTradeNo);
            yxUserBill.setStatus(1);
            yxUserBill.setIsPay(1);
            yxUserBillService.updateById(yxUserBill);
            YxUser yxUser=yxUserService.getById(yxUserBill.getUid());
            if(null !=yxUser){
                yxUser.setNowMoney(yxUser.getNowMoney().add(yxUserBill.getNumber()));
                yxUserService.updateById(yxUser);
                //塞入redis
                redisUtil.set("UserPrice" + yxUser.getUid(),yxUser.getNowMoney());
            }
        }
    }


    public static Map<String, String> updateMap(HttpServletRequest request){
        Map<String, String[]> map=request.getParameterMap();
        Map<String, String> params=new HashMap<String, String>();
        for (String key : map.keySet()) {
            String[] str=map.get(key);
            if(str!=null && str.length>0)
                params.put(key, str[0]);
        }
        return params;
    }
}
